package com.ls.controller;


import com.ls.entity.Result;
import com.ls.entity.UserLoginDTO;
import com.ls.pojo.User;
import com.ls.service.IUserService;
import com.ls.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoruan
 * @since 2023-04-24
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Integer id) {

        User user = userService.getById(id);
        return new Result(200, "查询商品信息成功", user);
    }


    @PostMapping("/login")
    public Result<String> login(@RequestBody UserLoginDTO userLoginDTO){
        //1、判断该用户的用户名和密码
       User user = userService.login(userLoginDTO);
       //2、如果为空登录失败，直接返回
       if (user==null){
           return new Result<>(500,"用户名/密码错误");
       }
       //3、如果登录成功，将用户名存储到redis中
        // 调用jwt的工具身材一个token
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",user.getUsername());
        map.put("userId",user.getId());
        String token = JwtUtil.createJWT("uuid", map, 1000L * 30 * 60);
        stringRedisTemplate.opsForValue().set("login:"+token,token,1800L, TimeUnit.SECONDS);

        //4、返回用户名
        return new Result<>(200,"登陆成功",token);
    }

}
